#!/usr/bin/env python3
import os
import sys
import time
import argparse
import urllib.parse
sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))

from core import utils


# vulnscan -i example.com -o '$WORKSPACE/vulnscan/details/[[0]]' -s '$WORKSPACE/vulnscan/summary.txt' -p '$PLUGINS_PATH'
def append_result(out, summary):
    data = utils.just_read(out, get_list=True)[1:]
    utils.just_write(summary, "\n".join(data))


def routine(args):
    parsed = urllib.parse.urlparse(args.input)
    target = parsed.netloc if parsed.netloc else parsed.path
    output = args.output
    strip_target = utils.strip_slash(target)
    plugin = args.plugin
    summary = args.summary

    cmd = f'sudo nmap --open -T4 -Pn -n -sSV -p- {target} --script {plugin}/nmap-stuff/vulners.nse --oA {output}'
    utils.print_info(f"Execute: {cmd}")

    if not utils.not_empty_file(f'{output}.csv'):
        os.system(cmd)
    if not utils.not_empty_file(f'{output}.xml'):
        utils.print_bad("Nmap command fail")
        sys.exit(-1)

    if not utils.not_empty_file(f'{output}.xml'):
        utils.print_bad("Error with nmap command")
        sys.exit(-1)

    os.system(
        f'python3 {plugin}/nmap-stuff/nmaptocsv.py -d "," -x {output}.xml -o {output}.csv')

    if not utils.not_empty_file(f'{output}.csv'):
        utils.print_bad("No open port found")
        sys.exit(-1)
    time.sleep(0.3)
    os.system(f'cat {output}.csv | csvlook --no-inference | tee {output}.txt')
    append_result(f'{output}.csv', summary)


parser = argparse.ArgumentParser(description="VulnScan alias")
parser.add_argument('-i', '--input', action='store', dest='input', help='input')
parser.add_argument('-o', '--output', action='store', dest='output', help='output')
parser.add_argument('-p', '--plugin', action='store', dest='plugin', help='plugin')
parser.add_argument('-s', '--summary', action='store',
                    dest='summary', help='summary')
args = parser.parse_args()
routine(args)
